<template>
  <div id="main">
    <!-- 导航栏 -->
    <van-sticky>
      <div class="navBar">
        <div class="navBar-left">
          <img :src="back" alt="" @click="handleBack" class="back" />
            <div v-if="user" class="avatar" :style="{backgroundImage: `url(${trendsDetail.avatar ? store.state.imgUrl + trendsDetail.avatar : logo})`}"></div>
            <!-- <van-image v-if="user" width="30" height="30" round :src=" trendsDetail.avatar ? store.state.imgUrl + trendsDetail.avatar : logo" /> -->
          <div v-if="user" style="font-size: 16px; color: #fff;padding:0 5px">
            {{ trendsDetail.name }}
          </div>
        </div>
        <div class="nav-btn" v-if="user && !trendsDetail.isOwn == 0">
          <div class="nav-btn-follow" v-if="!trendsDetail.isAttention" @click="handleLike(trendsDetail.userId)">
            <van-icon name="plus" />
            <span>关注</span>
          </div>
          <div class="nav-btn-followed" v-if="trendsDetail.isAttention" @click="handleLike(trendsDetail.userId)">
              <span>已关注</span>
          </div>
        </div>
      </div>
    </van-sticky>
    <div class="middle">
      <!-- 动态详情 -->
      <div class="content">
        <div class="info" ref="user">
          <div class="info-l" @click="gotoPersonal(trendsDetail)">
            <!-- <van-image
              width="38"
              height="38"
              style="border: 1px solid #ccc"
              round
              :src="trendsDetail.avatar ? store.state.imgUrl + trendsDetail.avatar : logo"
            /> -->
            <div class="avatar" :style="{backgroundImage: `url(${trendsDetail.avatar ? store.state.imgUrl + trendsDetail.avatar : logo})`}"></div>

            <div class="user">
              <div class="name">{{ trendsDetail.name }}<span class="me" v-if="trendsDetail.isOwn == 0">我</span></div>
              <div class="time-ip">
                {{ trendsDetail.createTime }} ·
                <span v-show="trendsDetail"></span> 来自{{
                  trendsDetail.ipProvince ? trendsDetail.ipProvince : '未知'
                }}
              </div>
            </div>
          </div>
          <div class="info-r" v-if="!trendsDetail.isOwn == 0">
            <van-button v-if="!trendsDetail.isAttention" icon="plus" color="#f29600" size="mini" @click="handleLike(trendsDetail.userId)"
              >关注</van-button
            >
            <van-button v-if="trendsDetail.isAttention" color="#ccc" plain size="mini" @click="handleLike(trendsDetail.userId)"
              ><span style="color: #000">已关注</span></van-button
            >
          </div>
        </div>
        <div class="content-main">
          <div class="main-title">{{ trendsDetail.title }}</div>
          <div   style="font-size: 14px; color: rgb(166, 166, 166); padding-top: 5px;line-height:20px">{{ trendsDetail.description }}</div>
          <div class="main-img">
            <div class="images-container" v-if="images.length > 0">
              <div
                v-for="(image, index) in images.slice(0, 9)"
                :key="index"
                class="image-item"
                @click="handleImageClick(images, index)"
                :style="{backgroundImage: `url(${image})`}"
              >
                <!-- <img
                  :src="image"
                  alt=""
                  width="100%"
                  height="100%"
                /> -->
                <div class="more" v-if="images.length > 9 && index === 8">
                  +{{ images.length > 9 ? images.length - 9 : "" }}
                </div>
              </div>
            </div>
          </div>
          <div class="shopping" v-if="showShopping">
            <div class="shop-btn">
              <span>购物推广</span>
            </div>
          </div>
        </div>
      </div>
      <!-- 评论 -->
      <div class="comment">
        <div class="comment-title">
          <span>评论</span>
          <span class="comment-num">{{ trendsDetail.commentNum }}</span>
        </div>
         <CommentList
               v-if="show"
               :token="token"
               :userId="trendsDetail.userId"
               ref="commentList"
              :source="trendsDetail.id"
              :list="commentList"
              class="article-list"
              @update-total-count="totalCommentCount = $event"
              @reply-click="onReplyClick"
              @del-comment="handleDel"
            ></CommentList>
      </div>
    </div>
    <!-- 评论框 -->
    <div class="field">
      <van-button
        class="comment-btn"
        type="default"
        round
        size="small"
        @click="handleClear"
        >我来说一下我的想法
      </van-button>
    </div>
    <!-- 底部导航 -->
    <div class="bottom">
       <div @click="gotodz(trendsDetail)" class="icon">
            <img :src="remarkList.urldz" width="15" v-if="!trendsDetail.isLike"/>
            <img :src="remarkList.urldzlove" v-if="trendsDetail.isLike" width="15"/>
            <div class="icon-txt">{{ trendsDetail.likeNum }}</div>
          </div>
          <div  class="icon">
            <img :src="remarkList.urlpl" width="15" @click="isPostShow = true"/>
            <div class="icon-txt">{{ trendsDetail.commentNum }}</div>
          </div>
          <div @click="addCollect(trendsDetail)" class="icon">
            <img :src="remarkList.urlsc" width="16" v-if="!trendsDetail.isCollect"/>
            <img :src="remarkList.urlsclove" width="16" v-if="trendsDetail.isCollect"/>
            <div class="icon-txt">{{ trendsDetail.collectNum }}</div>
          </div>
          
          <div @click="gotozf(trendsDetail)" class="icon">
            <img :src="remarkList.urlzf" width="15"/>
            <div class="icon-txt">分享</div>
          </div>
       </div>
    <!-- 评论发布 -->
    <van-popup v-model="isPostShow" position="bottom" round>
      <!-- 这里使用 v-if 的目的是让组件伴随着弹出层的显示进行渲染和销毁，防止加载过的组件不重新渲染导致数据不会重新加载的问题 🌟🌟  -->
      <PostComment
        v-if="isPostShow"
        :target="replyComment.id"
        @post-scucces="onPostSuccess"
        ref="myInput"
        @close="isPostShow = false"
        :art_id="trendsDetail.id"
      ></PostComment>
    </van-popup>
    <van-share-sheet
           v-model="showShare"
           title="立即分享给好友"
           :options="options"
           @select="onSelect"
       />
  </div>
</template>

<script>
import { ImagePreview } from "vant";
import CommentList from "@/views/share/components/comment-list";
import PostComment from "@/views/share/components/post-comment";
import store from '@/store'
import {addAuthorLike, updateLikes, addCollect, deleteComment} from '@/api/share'
import {Toast} from "vant";
import {Dialog} from 'vant';

import {antiShake} from '@/utils/antie.js'//防抖函数

export default {
  components: {
    CommentList,
    PostComment,
  },
  data() {
    return {
      trendsDetail: {
        isLike:'',
        isCollect:''
      },
      value: "",
      isfollow: true,
      basicUrl: "https://debug.yasee.com.cn",
      totalCommentCount: 0, // 评论数量
      showShopping: false,
      back: require("@/assets/search/back.png"),
      // headImg: require("@/assets/touxiang.png"),
      img: require("@/assets/search/trend.jpg"),
      images: [],
      user: false,
      remarkList: {
        urlsclove: require('@/assets/remark/sc_love.png'),
        urldzlove: require('@/assets/remark/dz_love.png'),
        urldz: require('@/assets/remark/dz.png'),
        urlpl: require('@/assets/remark/pl.png'),
        urlsc: require('@/assets/remark/sc.png'),
        urlzf: require('@/assets/remark/zf.png'),
      },
      form: {},
      file: "",
      commentList: [],
      replyComment: {}, //  当前回复评论对象
      isPostShow: false, // 发布评论
      id:'',
      store:store,
      sourceId:'',
      show: false,
      token:'',
       options: [
        {name: '微信', icon: 'wechat', openType: 'share'},
        {name: 'QQ', icon: 'qq', openType: 'share'},
        {name: '微博', icon: 'weibo'},
        {name: '复制链接', icon: 'link'},
      ],
      showShare:false,
      logo: require("@/assets/tx.png"),
      reply:false//判断点击的按钮是否是底部按钮
      
    };
  },
  mounted() {
    window.addEventListener("scroll", this.handleScrollx, true);
     window["getInfoFromFlutter"] = (info) => {
      if (JSON.parse(info).action === 'share') {
           this.getInfoFromFlutter(info);
        
      }
    };
     this.id = !this.getParam("id") ? "" : this.getParam("id")
    this.token = !this.getParam("token") ? "" : decodeURI(this.getParam("token"))
   
    this.getDataList()
    
    // this.getComments()
  },
  beforeDestroy() {    //在加载时添加了scroll监听，如果不销毁，到下一个页面时，没有主动销毁，会报错'offsetTop' of undefined。因此，需要在页面跳转前销毁此监听
      window.removeEventListener("scroll", this.handleScrollx, true)
  },
  created() {},
  methods: {
    getParam(name) {
            if (window.location.hash.indexOf("?") != -1) {
                const query = window.location.hash.split("?")[1];
                const vars = query.split("&");
                for (var i = 0; i < vars.length; i++) {
                    var pair = vars[i].split("=");
                        if (pair[0] == name) {
                            return pair[1];
                        }
                    }
            } else {
                return "";
            }
    },
    getInfoFromFlutter(info) {
      let data = JSON.parse(info)
        if (data.param.succeed == 1) {
          this.$toast.success('分享成功')
        } else {
          this.$toast.fail('已取消分享')
        }
    },
    handleScrollx() {
      //监听头部导航
        if (this.$refs.user.getBoundingClientRect().top <= 30) {
          this.user = true;
        } else {
          this.user = false;
        }
      // }
    },
    handleBack() {
      this.$router.go(-1);
      let message = {
        action: 'showBottom',
        param: {}
      }
      getInfoFromVue.postMessage(JSON.stringify(message))
    },
    handleImageClick(item, index) {
      const imageUrls = item.map((image) => image);
      ImagePreview({
        images: imageUrls,
        startPosition: index,
        showIndicators:true,
        closeable:true
      });
    },
    onReplyClick(comment) {
      this.reply = false
      // 获取当前评论
      this.replyComment = comment;
      // 打开回复评论弹窗
      this.isPostShow = true;
    },
    // 发布评论成功
    onPostSuccess(comment) {
      const commentNew = comment
      if (this.reply) {
        commentNew.reply = ''
      }
      this.$store.commit('share/UPDATE_COMMENT_LIST', commentNew)
      // 更新评论的数量
      // this.totalCommentCount++;
      this.trendsDetail.commentNum += 1
      // 关闭发布评论弹出层
      this.isPostShow = false;
    },
    //删除评论
    handleDel(comment){
      this.$store.commit('share/DELETE_COMMENT_LIST', comment)
      console.log('获取要删除评论',comment)
      if (comment.children.length > 0) {//如果子集有评论则删除数量应该加上子集数量
        this.trendsDetail.commentNum -= 1 + comment.children.length
      }else{
         this.trendsDetail.commentNum -= 1
      }
      deleteComment(comment.id).then((res) => {
        if (res.code === 0) {
          this.$toast('已删除该评论')
        }
      }).catch((err) => {
        this.$toast('评论删除失败')
      })
    },
    handleOpen() {
      this.isPostShow = true;
    },
    // 获取动态详情
    getDataList(){
        const param = { 
          id:  this.id,
          token:this.token 
        };
        this.$store.dispatch("queryDynamicAction", param).then((res) => {
          if (res) {
            this.show = true
            this.$nextTick(() => {
              this.$refs.commentList.init()
           })
            this.trendsDetail = res;
            this.images = res.children  ?  res.children : [];
          }
        })
    },
    handleLike: antiShake( function (id){//关注/取消关注
     if (!this.trendsDetail.isAttention) {
        this.likeSure(id)
        this.$toast.success("关注成功");
     }else{
      this.tipIsAttention(id)
     }
    }),
    likeSure(id){
       const data={
        id:id,
        token:this.token
      }
      addAuthorLike(data).then((res)=>{
        
        this.trendsDetail.isAttention = !this.trendsDetail.isAttention
          // this.getDataList()
      })
    },
     //取消关注提示
    tipIsAttention(id){
      Dialog.confirm({
        title: '提示',
        message: '您确定要取消关注该用户吗？',
        confirmButtonColor: 'rgba(242, 150, 0, 1)'
      }).then(() => {
        this.likeSure(id)
        this.$toast.success("取关成功");
         
      }).catch(err => {
        
      })
    }, 
    //点赞
    gotodz: antiShake( function (item) {
      let data = {
        id: item.id,
        type: 0 ,//文章，动态，视频是0 评论是1
        token:this.token
      }
      updateLikes(data).then((res) => {
        if (res.code == 0) {
          if (item.isLike) {
          this.$toast.fail('已取消点赞')
            
          }else{
          this.$toast.success('点赞成功')
           
          }
          this.trendsDetail.isLike = ! this.trendsDetail.isLike
          this.trendsDetail.likeNum += this.trendsDetail.isLike ? 1 : -1;
        }
      }).catch((err) => {
        this.$toast.fail('点赞失败')
      })
     }),
    // 收藏
    addCollect: antiShake( function (item,index) {
        let data = {
          id: item.id,
          type: 0 ,//文章，动态，视频是0 评论是1
          token:this.token
      }
      addCollect(data).then((res) => {
        if (res.code === 0) {
          // console.log(item.isCollect)
            if (item.isCollect) {
              this.$toast.fail('已取消收藏')
            }else{
              this.$toast.success('收藏成功')
            }
            this.trendsDetail.isCollect = !this.trendsDetail.isCollect
            this.trendsDetail.collectNum += this.trendsDetail.isCollect ? 1 : -1;
        }
      }).catch((err) => {
        this.$toast.fail('收藏失败')
      })
    }),
    // 分享
    gotozf(item){
      //  this.showShare = true
       let message = {
        action: 'share',
        param: {
          type: "link",            //必填
          title: item.title,          //必填
          name: '/home/share/index',
          subtitle: item.description,
          link: "http://192.168.110.105:9033/#/trendsDetail?"+item.id,//动态列表的详情?id:''
          callback: 1
        }
      }
      // console.log(message)
      getInfoFromVue.postMessage(JSON.stringify(message))
    },
     onSelect(option) {
      Toast(option.name);
      if (option.name === '微信') {
        window.location.href = 'weixin://';
      } else if (option.name === 'qq') {
        //跳转qq链接
      } else if (option.name === '微博') {
        //跳转微博的链接
      } else if (option.name === '复制链接') {
        //复制链接
        this.copyLink()
      }
      this.showShare = false;
    },
     copyLink() {
      const link = window.location.href; // 要复制的链接
      // console.log(link)
      // 使用Vant的Clipboard组件的copy方法复制链接
      // this.$vant.Clipboard.copy(link)
      //   .then(() => {
      //     this.$toast('链接已复制'); // 复制成功提示
      //   })
      //   .catch(() => {
      //     this.$toast('复制失败'); // 复制失败提示
      //   });
      let inputNode = document.createElement('input')  // 创建input
      inputNode.value = link // 赋值给 input 值
      document.body.appendChild(inputNode) // 插入进去
      inputNode.select() // 选择对象
      document.execCommand('Copy') // 原生调用执行浏览器复制命令
      inputNode.className = 'oInput'
      inputNode.style.display = 'none' // 隐藏
      this.$toast.success('复制成功')
    },
    // 清除回复评论缓存数据
    handleClear(){
      this.isPostShow = true
      this.reply = true
      this.replyComment.id = ''
    },
    // 跳转到主页
    gotoPersonal(item) {
      if (item.isOwn == 0) {//跳转到自己的个人主页
        this.$router.push({path: '/personalPage',query:{}})
      }else{//跳转到别人主页的个人主页
        this.$router.push({path: '/visitPersonal',query:{obj:JSON.stringify(item)}})
      }
      
      // let message = {
      //   action: 'hiddenBottom',
      //   param: {}
      // }
      // getInfoFromVue.postMessage(JSON.stringify(message))
    }
    
  },
};
</script>

<style lang="less" scoped>
#main {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;

  .navBar {
    height: 40px;
    background: #f29600;
    display: flex;
    padding: 2px 19px;
    align-items: center;
    justify-content: space-between;
    .navBar-left {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      .avatar{
          border: 1px solid #ebeef5;
          background-size: 100%;
          width: 30px;
          height: 30px;
          border-radius: 50%;
          opacity: 1;
          margin-left:10px;
          background-repeat: no-repeat;
          background-position: center;
          background-size: cover;
      }
    }
    .van-image {
      margin: 0 10px;
    }
    .nav-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 12px;
      .nav-btn-follow {
        background: #fff;
        color: #f29600;
        border: 1px solid #fff;
        padding: 3px;
      }
      .nav-btn-followed {
        background: #f29600;
        color: #fff;
        border: 1px solid #fff;
        padding: 3px;
      }
    }
  }
  .content {
    padding: 20px 10px 0 10px;
    .info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      // font-size: 12px;
      .info-l {
        display: flex;
        height: 38px;
        align-items: center;
        justify-content: flex-start;
        .avatar{
          border: 1px solid #ebeef5;
          background-size: 100%;
          width: 38px;
          height: 38px;
          border-radius: 50%;
          opacity: 1;
          margin-right:5px;
          background-repeat: no-repeat;
          background-position: center;
          background-size: cover;
        } 
        .user {
          padding: 0 10px;
          .name {
            font-size: 16px;
            font-size: 16px;
            font-weight: 500;
            letter-spacing: 0px;
            line-height: 23.17px;
            color: rgba(0, 0, 0, 1);
            text-align: left;
            vertical-align: top;
            .me{
              background: #ccc6;
              padding: 0 3px;
              font-size: 14px;
              border-radius: 5px;
              color: #9b9494;
              margin: 0 5px;
            }
          }
          .time-ip {
            font-size: 12px;
            font-weight: 400;
            letter-spacing: 0px;
            line-height: 17.38px;
            color: rgba(102, 102, 102, 1);
          }
        }
      }
    }
    .content-main {
      padding: 17px 0;
      padding-bottom: 0;
      .main-title {
        font-size: 17px;
        font-weight: 400;
        letter-spacing: 0px;
        line-height: 24.62px;
        color: rgba(0, 0, 0, 1);
        text-align: left;
        // vertical-align: top;
        padding: 3px 0 3px 0;
      }
      .main-img {
        position: relative;
        width: 100%;
        height: auto;
        .images-container {
          display: flex;
          flex-wrap: wrap;
        }
        .image-item {
          width: calc(33.33% - 6px);
          height: 114px;
          margin: 3px;
          background-size: cover;
          background-position: center;
          border-radius: 5px;
          position: relative;
          overflow: hidden;
          background-repeat: no-repeat;
        background-position: center;
        background-size: cover;
          .img {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            min-width: 100%;
            min-height: 100%;
          }
        }
        .more {
          position: absolute;
          bottom: 0;
          right: 0;
          width: 36px;
          height: 26px;
          opacity: 1;
          border-radius: 5px 0px 5px 0px;
          background: rgba(0, 0, 0, 0.47);
          font-size: 12px;
          font-weight: 400;
          letter-spacing: 0.5px;
          line-height: 26px;
          color: rgba(255, 255, 255, 1);
          text-align: center;
        }
      }
      .shopping {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 20px 45px;
        border-bottom: 0.45px solid rgba(229, 229, 229, 1);
        .shop-btn {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 300px;
          padding: 5px 20px;
          border: 1px solid #ccc;
          border-radius: 20px;
          font-size: 17px;
          color: rgba(153, 153, 153, 1);
          cursor: pointer;
        }
      }
    }
  }
  .comment {
    padding: 5px 17px 0 17px;
    .comment-title {
      font-size: 17px;
      font-size: 17px;
      font-weight: 500;
      letter-spacing: 0px;
      line-height: 24.62px;
      .comment-num {
        padding-left: 5px;
      }
    }
  }
  .bottom {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 20px;
    background: #fff;
    display: flex;
    justify-content: space-between;
    padding: 8px 17px;
    font-size: 12px;
    .icon {
      display: flex;
      align-items: center;
      justify-content: center;
      .icon-txt {
        margin-left: 5px;
      }
    }
  }
  .field {
    position: fixed;
    bottom: 36px;
    left: 0;
    right: 0;
    height: 20px;
    background: #fff;
    display: flex;
    justify-content: space-between;
    padding: 8px 17px;
    font-size: 12px;
    background: #fff;
    //border-top: 1px solid #d8d8d8;
    display: flex;
    justify-content: center;
    align-items: center;
    .comment-btn {
      width: 357px;
      height: 30px;
      font-size: 15px;
      color: #a7a7a7;
      border-radius: 15px;
      border: solid 1px #eeeeee;
      background: #f7f8fa;
    }
  }
  // .input{
  //     // padding: 0 10px;
  //     position: fixed;
  //     bottom: 72px;
  //     left: 0;
  //     right: 0;
  //     height: 20px;
  //     background: #fff;
  //     font-size: 12px;
  //     display: flex;
  //     align-items: center;
  //     justify-slclsj: center;
  //     flex-direction: column;
  // }

  .middle {
    flex: 1;
    overflow-x: hidden;
    padding-bottom: 72px;
  }
}
</style>
